package com.kingstar.ceres.data.impl;

import com.kingstar.ceres.data.bo.FileImportBO;
import com.kingstar.ceres.data.constant.FileImportConstants;
import com.kingstar.ceres.data.facade.AbstractDataInitFacade;
import com.kingstar.ceres.data.handler.ITaskLockHandler;
import com.kingstar.ceres.data.helper.CsvImportHelper;
import com.kingstar.ceres.data.properties.FileParseProperties;
import com.kingstar.ceres.data.remote.ConnectionFactory;
import com.kingstar.ceres.data.util.FileImportUtils;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
public class DefaultCsvDataInitFacade extends AbstractDataInitFacade {

    @Resource
    private FileParseProperties properties;

    @Resource
    private CsvImportHelper importHelper;

    public DefaultCsvDataInitFacade(ITaskLockHandler taskLockHandler, ConnectionFactory connectionFactory) {
        super.connectionFactory=connectionFactory;
        super.taskLockHandler = taskLockHandler;
    }

    public boolean fileDataProcess(FileImportBO bo) throws Exception {

        return doProcess(bo,properties.getCsv().getParseCoreSize(), FileImportConstants.FILE_TYPE_CSV,importHelper::process);
    }

    @Override
    protected void checkFileComplete(FileImportBO bo) {
        if(!downloadFile(bo)){
            throw new RuntimeException("文件下载失败");
        }
        String csvOkFileName = properties.getCsv().getOkFileName();
        Boolean flag = properties.getCsv().getNeedCheckOk();
        log.info("csv check complete,need:{},flagName:{}",flag,csvOkFileName);
        if (!flag){
            return;
        }
        String batchPath = bo.getBatchPath();
        String dir = FileImportUtils.parseParentDir(properties.getCsv().getFileDir(), batchPath);
        Path path = Paths.get(dir, csvOkFileName);
        checkFileExist(path);
    }

    public void init(){
        super.register(FileImportConstants.FILE_TYPE_CSV,this);
        log.info("register CsvDataInitFacadeImpl success");
    }
}
